package com.bidevalution.controller.api;

import com.bidevalution.business.service.BeSectionReportService;
import com.bidevalution.dao.entity.BeSectionReport;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.config.PropertiesTookit;
import com.qtp.core.model.Response;
import com.qtp.core.util.FileUtils;
import com.qtp.core.util.OConvertUtils;
import com.qtp.core.util.ParamsUtil;
import com.qtp.core.util.ZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * 标段报表控制层
 *
 * @author 查慧英
 * @date 2019-11-12 10:07
 */
@RestController
@RequestMapping("/beSectionReport")
@Api(description = "标段报表相关操作Controller")
public class BeSectionReportController extends BaseController {
    private Logger logger = Logger.getLogger(getClass());
    private static final String REDIS_KEY_REPORT_PARAM = "%s_%s_%s";
    private static final String REPORT_PATH_PARAM = "%s%s";
    private static final String EXPORT_PATH = PropertiesTookit.getValue("ureport.export.path");
    private static final String ZIP_PATH = PropertiesTookit.getValue("ureport.zip.path");
    private static final String EXCEL_SUFFIX = PropertiesTookit.getValue("ureport.excel.suffix");
    private static final String EXCEL_ZIP_NAME = "excel.zip";
    private static final String PDF_ZIP_NAME = "pdf.zip";
    private static final String SECTION_ID = "sectionId";
    private static final String REPORT_PATHS = "reportPaths";
    private static final String USER_GUID = "userGuid";
    private static final String IDS = "ids";
    private static final String STEP_CODE = "stepCode";
    private static final String EXCEL_NAME_FORMAT="%s.%s";
    private static final String LOGIN_NAME = "loginName";
    private static final String SECTION_CODE = "sectionCode";
    private static final String FILE_PATH = "file:zbgsnr.ureport.xml,file:gsnrpbzjmd.ureport.xml";
    @Autowired(required = false)
    BeSectionReportService beSectionReportService;

    /**
     * 获取开标列表信息
     *  @param request
     * @param response
     */
    @ApiOperation(value = "获取报表列表", notes = "获取报表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping("/getBeSectionReportList")
    public Response<List<BeSectionReport>> getBeSectionReportList(HttpServletRequest request, HttpServletResponse response) {
        setHttpServletResponse(response);
        try {
            String userGuid = request.getHeader(USER_GUID);
            // 获取请求中的参数
            Map<String, Object> paramsMap = ParamsUtil.getParamsValue(request);
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            if (tsUser != null) {
                paramsMap.put(LOGIN_NAME, tsUser.getLoginName());
                return beSectionReportService.getBeSectionReportList(paramsMap);
            } else {
                return Response.fail("获取专家账号登录信息失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
    @ApiOperation(value = "设置打印报表的参数", notes = "设置打印报表的参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = IDS, value = "报表ids", paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/setPrintParam")
    public Response setPrintParam(HttpServletRequest request,@RequestParam(IDS) String ids) {
        String userGuid = request.getHeader(USER_GUID);
        String sectionId = request.getParameter(SECTION_ID);
        try {
            if (OConvertUtils.isNotEmpty(ids)) {
                RedisAccess.add(ids, REDIS_KEY_REPORT_PARAM, userGuid, sectionId, IDS);
            }
            return Response.ok(userGuid);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.fail("操作失败！");
        }


    }
    @ApiOperation(value = "打印报表", notes = "打印报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = REPORT_PATHS, value = "所有打印的报表路径", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = STEP_CODE, value = "环节编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = USER_GUID, value = "用户guid", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping(value = "/printPdf")
    public Response printPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf");
        Map<String,Object> parameters = ParamsUtil.getParamsValue(request);
        String userGuid = request.getParameter(USER_GUID);
        TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
        if (tsUser != null) {
            OutputStream os = response.getOutputStream();
            parameters.put(LOGIN_NAME, tsUser.getLoginName());
            return beSectionReportService.printPdf(parameters, os);
        } else {
            return Response.fail("获取专家信息失败！");
        }
    }
    @ApiOperation(value = "批量打印报表", notes = "批量打印报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = IDS, value = "报表ids", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = USER_GUID, value = "用户guid", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/batchPrintPdf")
    public Response batchPrintPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf");
        Map<String,Object> parameters = ParamsUtil.getParamsValue(request);
        String userGuid = request.getParameter(USER_GUID);
        TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
        if (tsUser != null) {
            parameters.put(LOGIN_NAME, tsUser.getLoginName());
            OutputStream os = response.getOutputStream();
            return beSectionReportService.batchPrintPdf(parameters, os);
        } else {
            return Response.fail("获取专家信息失败！");
        }
    }
    @ApiOperation(value = "批量导出报表", notes = "批量导出报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = USER_GUID, value = "用户guid", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping(value = "/exportPdf")
    public Response exportPdf(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/pdf");
        Map<String,Object> parameters = ParamsUtil.getParamsValue(request);
        try{
            setParams(request, parameters);
            String userGuid = request.getParameter(USER_GUID);
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            if (tsUser != null) {
                parameters.put(LOGIN_NAME, tsUser.getLoginName());
                //导出pdf
                beSectionReportService.exportPdf(parameters, EXPORT_PATH);
                String zipFile = String.format(REPORT_PATH_PARAM, ZIP_PATH, PDF_ZIP_NAME);
                //压缩pdf
                ZipUtil.zipCompressing(zipFile, new File(EXPORT_PATH));
                //删除生成的pdf文件
                FileUtils.delFiles(new File(EXPORT_PATH));
                //下载压缩包到本地
                FileUtils.downloadFile(zipFile, PDF_ZIP_NAME, request, response);
                return Response.ok();
            } else {
                return Response.fail("获取专家信息失败！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.fail(e.getMessage());
        }
    }

    private void setParams(HttpServletRequest request, Map<String,Object> parameters) {
        String userGuid = request.getParameter(USER_GUID);
        String sectionId = request.getParameter(SECTION_ID);
        String ids = RedisAccess.getValue(String.class, REDIS_KEY_REPORT_PARAM, userGuid, sectionId, IDS);
        parameters.put(IDS, ids);
    }

    @ApiOperation(value = "批量导出Excel", notes = "批量导出Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = USER_GUID, value = "用户guid", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping(value = "/excel")
    public Response exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String,Object> parameters = ParamsUtil.getParamsValue(request);
        try{
            setParams(request, parameters);
            String userGuid = request.getParameter(USER_GUID);
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            if (tsUser != null) {
                parameters.put(LOGIN_NAME, tsUser.getLoginName());
                //导出Excel
                beSectionReportService.exportExcel(parameters, EXPORT_PATH);
                String zipFile = String.format(REPORT_PATH_PARAM, ZIP_PATH, EXCEL_ZIP_NAME);
                //压缩Excel
                ZipUtil.zipCompressing(zipFile, new File(EXPORT_PATH));
                //删除生成的Excel文件
                FileUtils.delFiles(new File(EXPORT_PATH));
                //下载压缩包到本地
                FileUtils.downloadFile(zipFile, EXCEL_ZIP_NAME, request, response);
                return Response.ok();
            } else {
                return Response.fail("获取专家信息失败！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.fail(e.getMessage());
        }

    }
    @ApiOperation(value = "批量导出ExcelSheet", notes = "批量导出ExcelSheet")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = USER_GUID, value = "用户guid", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping(value = "/excelSheet")
    public Response exportExcelSheet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String,Object> parameters = ParamsUtil.getParamsValue(request);
        String sectionId = request.getParameter("sectionId");
        try{
            setParams(request, parameters);
            String userGuid = request.getParameter(USER_GUID);
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            if (tsUser != null) {
                parameters.put(LOGIN_NAME, tsUser.getLoginName());
                //导出Excel
                beSectionReportService.exportExcelSheet(parameters, EXPORT_PATH);
                //下载压缩包到本地
                String excelName = String.format(EXCEL_NAME_FORMAT, sectionId, EXCEL_SUFFIX);
                String excelPath = String.format(REPORT_PATH_PARAM, EXPORT_PATH, excelName);
                FileUtils.downloadFile(excelPath, excelName, request, response);
                return Response.ok();
            } else {
                return Response.fail("获取专家信息失败！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "推送报表", notes = "推送报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SECTION_ID, value = "标段Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = SECTION_CODE, value = "项目编号", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/pushPdf")
    public Response pushPdf(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/pdf");
        Map<String,Object> parameters = ParamsUtil.getParamsValue(request);
        parameters.put(REPORT_PATHS, FILE_PATH);
        return beSectionReportService.pushPdf(parameters, ZIP_PATH);
    }
}
